package org.seeplnframework.skyeye.common.model;

import com.alibaba.fastjson.JSONArray;
import com.google.common.base.Splitter;
import lombok.Builder;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ly
 * @date 2023/2/20
 */
@Data
@Builder
public class RoutingForCurrentAlarmMessage {

    /**
     * 当前报警消息目标推送群
     */
    private String hook;

    /**
     * 异常信息关键字 包含多个 格式：关键字1,关键字2...
     */
    private String keywords;

    /**
     * 是否将当前报警消息只推到业务异常提示群 默认false
     */
    private boolean remindForBusiness;

    public static RoutingForCurrentAlarmMessage create(String message, String configHooks) {
        WechatConfigData target = findTargetForThisMessage(message, JSONArray.parseArray(configHooks, WechatConfigData.class));
        return RoutingForCurrentAlarmMessage
                .builder()
                .hook(target == null ? "" : target.getKey())
                .keywords(target == null ? "" : target.getKeywords())
                .remindForBusiness(target == null ? false : target.isReminder())
                .build();
    }

    private static WechatConfigData findTargetForThisMessage(String message, List<WechatConfigData> hooks) {
        List<WechatConfigData> forReminder = hooks
                .stream()
                .filter(it -> !StringUtils.isEmpty(it.getKeywords()) && it.isReminder())
                .collect(Collectors.toList());
        List<WechatConfigData> forGlobal = hooks
                .stream()
                .filter(it -> !it.isReminder())
                .collect(Collectors.toList());
        WechatConfigData hitReminder = forReminder
                .stream()
                .filter(it -> hit(message, it.getKeywords()))
                .findFirst()
                .orElse(null);
        return Optional.ofNullable(hitReminder).orElseGet(() -> CollectionUtils.isEmpty(forGlobal) ? null : forGlobal.get(0));
    }

    private static boolean hit(String message, String keywords) {
        return Splitter
                .on(",")
                .splitToList(keywords)
                .parallelStream()
                .anyMatch(it -> message.contains(it));
    }
}
